package rs.parser;

import java.util.ArrayList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import rs.domain.Track;
import rs.util.Requester;
import rs.util.TuningParameters;

/* Classe responsabile del parsing di un JSON relativo ai brani recenti di un utente */
public class RecentTracksParser {

	public List<Track> parse(Requester app, String url, String response) {
		List<Track> track_list = new ArrayList<Track>();
		if (!response.substring(2,7).equals("error")) {
			try {					
				JSONObject json = (JSONObject) new JSONParser().parse(response);
				JSONObject recenttracks = (JSONObject) json.get("recenttracks");

				JSONObject attr = (JSONObject) recenttracks.get("@attr");
				if (attr == null) {
					return track_list;
				}			
				int totalPages = Integer.parseInt((String) attr.get("totalPages"));			
				String prefix_url = url.substring(0, url.length() - 1);			
				track_list.addAll(this.extractTracks(response));

				for (int i = 2; i <= TuningParameters.RECENT_MAX_PAGES && i <= totalPages; i++) {
					track_list.addAll(this.extractTracks(app.send(prefix_url + i)));
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return track_list;
	}

	private List<Track> extractTracks(String response) {
		List<Track> track_list = new ArrayList<Track>();
		try {	
			JSONObject json = (JSONObject) new JSONParser().parse(response);
			JSONObject recenttracks = (JSONObject) json.get("recenttracks");
			
			Object tracks = recenttracks.get("track");
			if (tracks instanceof JSONObject) {
				track_list.add(this.getTrack(tracks));
			}
			else {
				for (Object obj : (JSONArray)tracks) {
					track_list.add(this.getTrack(obj));
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return track_list;
	}

	private Track getTrack(Object obj) {
		JSONObject json_obj = (JSONObject) obj;
		JSONObject artist = (JSONObject) json_obj.get("artist");
		String track_name = (String) json_obj.get("name");
		String track_artist = (String) artist.get("#text");
		return new Track(track_name, track_artist);
	}

}
